package com.wlw.layoutmanager.adapters;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {
    private int layoutResId;
    public List<T> mData;
    private OnItemClickListener onItemClickListener;

    public BaseAdapter(int layoutResId, List<T> data) {
        this.layoutResId = layoutResId;
        if (data != null)
            this.mData = data;
        else
            mData = new ArrayList<>();

    }

    public void setData(List<T> data) {
        if (data != null) {
            mData = data;
        }
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new BaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(layoutResId, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, final int position) {
        final View itemView = holder.itemView;
        if (onItemClickListener != null) {
            itemView.setOnClickListener(it -> onItemClickListener.onItemClick(itemView, position));
        }
        onBindView(holder, mData.get(position), position);

    }

    public abstract void onBindView(BaseViewHolder holder, T t, int position);

    @Override
    public int getItemCount() {
        return mData != null ? mData.size() : 0;
    }

    public OnItemClickListener getOnItemClickListener() {
        return onItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View itemView, int position);
    }
}
